package activity.setting.PlanVideo;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.hichip.data.HiDeviceInfo;
import com.xw.repo.BubbleSeekBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import base.HiActivity;
import bean.MyCamera;
import bean.TimeArrayBean;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import custom.SwitchButton;
import custom.dialog.NiftyDialogBuilder;
import utils.HiTools;

public class PlanVideoActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.title) TitleView title;
    private MyCamera mMyCamera;
    @BindView(R.id.rl_simple_set) RelativeLayout rl_simple_set;
    @BindView(R.id.rl_advanced_set) RelativeLayout rl_advanced_set;

    @BindView(R.id.rb_simple_check) CheckBox rb_simple_check;
    @BindView(R.id.rb_advance_check) CheckBox rb_advance_check;

    private HiChipDefines.HI_P2P_S_REC_AUTO_PARAM rec_param;
    private HiChipDefines.HI_P2P_QUANTUM_TIME quantum_time;

    @BindView(R.id.switch_record) SwitchButton switch_record;
    private ArrayList<TimeArrayBean> mBeans = new ArrayList<>();
    private int recordTime = HISI_TIME;
    private static final int GOKE_TIME = 600;
    private static final int HISI_TIME = 900;
    @BindView(R.id.tv_application) TextView tv_application;
    @BindView(R.id.sb_sensitivity) SeekBar sb_sensitivity;
    @BindView(R.id.tv_sensitivity_rate) TextView tv_sensitivity_rate;

    @BindView(R.id.ll_planvideo_content) LinearLayout ll_planvideo_content;
    @BindView(R.id.tv_time_range) TextView tv_time_range;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_planvideo;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMyCamera != null) {
            mMyCamera.registerIOSessionListener(this);
            showjuHuaDialog();
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE, new byte[0]);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
    }

    private void setListeners() {
        rl_simple_set.setOnClickListener(this);
        rl_advanced_set.setOnClickListener(this);
        tv_application.setOnClickListener(this);
        sb_sensitivity.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_sensitivity_rate.setText((progress + 15) + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                rec_param.u32FileLen = seekBar.getProgress() + 15;
                showjuHuaDialog();
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_PARAM, rec_param.parseContent());
            }
        });
    }

    private void getIntentData() {
        String str_uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        for (MyCamera camera : HiDataValue.CameraList) {
            if (camera.getUid().equals(str_uid)) {
                mMyCamera = camera;
                break;
            }
        }
        if (HiTools.cameraWhetherNull(mMyCamera, this)) return;
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_REC_AUTO_PARAM, new byte[0]);
    }

    private void initViewAndData() {
        title.setTitle(getString(R.string.sd_plan_video));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                }
            }
        });
        recordTime = mMyCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_GOKE ? GOKE_TIME : HISI_TIME;
        sb_sensitivity.setMax(recordTime - 15);
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) String recording_time_str = String.format(getString(R.string.time_format), recordTime);
        tv_time_range.setText(recording_time_str);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_simple_set:
                if (rb_simple_check.isChecked()) return;
                NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(this);
                dialog.withMessageLayoutHWrapW(HiTools.dip2px(this, 280));
                dialog.withTitle(getString(R.string.tip_reminder)).withMessage(getString(R.string.clear_time));
                dialog.withButton1Text(getString(R.string.cancel)).withButton2Text(getString(R.string.confirm));
                dialog.show();
                dialog.setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.setButton2Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        handSimpleSet();
                    }
                });
                break;
            case R.id.rl_advanced_set://高级设置
                Intent intent = new Intent(PlanVideoActivity.this, PlanVideoAdvanceSetActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                startActivity(intent);
                break;
            case R.id.tv_application:
                handApplication();
                break;
        }

    }

    private void handSimpleSet() {
        for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 48; j++) {
                quantum_time.sDayData[i][j] = 80;
            }
        }
        quantum_time.u32QtType = HiChipDefines.HI_P2P_TYPE_PLAN;
        showjuHuaDialog();
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE, quantum_time.parseContent());
        rb_simple_check.setChecked(true);
        rb_advance_check.setChecked(false);
    }

    private void handApplication() {
        if (quantum_time == null || rec_param == null) {
            return;
        }
        int rec_time_val = 0;
        rec_time_val = sb_sensitivity.getProgress();
        if (rec_time_val < 15 || rec_time_val > recordTime) {
            Toast.makeText(this, String.format(getText(R.string.tips_recording_time_range).toString(), recordTime), Toast.LENGTH_LONG).show();
            return;
        }
        rec_param.u32Enable = switch_record.isChecked() ? 1 : 0;
        rec_param.u32FileLen = rec_time_val;
        showjuHuaDialog();
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_PARAM, rec_param.parseContent());
        if (rl_simple_set.isSelected()) {
            for (int i = 0; i < 7; i++) {
                for (int j = 0; j < 48; j++) {
                    quantum_time.sDayData[i][j] = 80;
                }
            }
            quantum_time.u32QtType = HiChipDefines.HI_P2P_TYPE_PLAN;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE, quantum_time.parseContent());
        }
    }

    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handIOCTRLSuccess(msg);
                    } else {//失败

                    }
                    break;
            }
        }
    };


    private void handIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_REC_AUTO_PARAM:
                rec_param = new HiChipDefines.HI_P2P_S_REC_AUTO_PARAM(data);
                sb_sensitivity.setProgress(rec_param.u32FileLen);
                tv_sensitivity_rate.setText(rec_param.u32FileLen + "");
                switch_record.setChecked(rec_param.u32Enable == 1 ? true : false);
                if (rec_param.u32Enable == 1) {
                    showViewContent();
                }
                switch_record.setOnCheckedChangeListener(this);
                break;
            case HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE:
                dismissjuHuaDialog();
                if (mBeans != null && mBeans.size() > 0) {
                    mBeans.clear();
                }
                handData(data);
                handView();
                break;
            case HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE:
                dismissjuHuaDialog();
                break;
            case HiChipDefines.HI_P2P_SET_REC_AUTO_PARAM:
                dismissjuHuaDialog();
                break;
        }
    }

    private void handView() {
        int i = 0;
        for (TimeArrayBean bean : mBeans) {
            if (bean.mIsAllDay) {
                i++;
            }
        }
        if (i == 7) {//全天
            rb_simple_check.setChecked(true);
            rb_advance_check.setChecked(false);
        } else {
            rb_simple_check.setChecked(false);
            rb_advance_check.setChecked(true);
        }
    }

    private void handData(byte[] data) {
        quantum_time = new HiChipDefines.HI_P2P_QUANTUM_TIME(data);
        byte[][] array = quantum_time.sDayData;
        boolean isStart = false;
        for (int i = 0; i < 7; i++) {
            TimeArrayBean timeArrayBean = new TimeArrayBean();
            boolean isAllDay = true;
            mBeans.add(timeArrayBean);
            timeArrayBean.setTitle(i);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < 48; j++) {
                if (array[i][j] == 80) {//80 代表 —P —开
                    isStart = true;
                    if (isStart) {
                        if (TextUtils.isEmpty(sb.toString())) {
                            if (j == 47) {
                                sb.append("23:30-23:59");
                                timeArrayBean.arrs.add(sb.toString());
                            } else {
                                sb.append(jToStr(j) + "-");
                            }
                        }
                    }
                } else if (array[i][j] == 78) {//78 代表—N—关
                    isAllDay = false;
                    if (isStart) {
                        isStart = false;
                        if (!TextUtils.isEmpty(sb.toString())) {
                            sb.append(jToStr(j));
                            timeArrayBean.arrs.add(sb.toString());
                            sb = new StringBuffer();
                        }
                    }
                }
            }
            timeArrayBean.mIsAllDay = isAllDay;
        }

        for (TimeArrayBean bean : mBeans) {
            StringBuffer sb = new StringBuffer();
            for (String str : bean.getArrs()) {
                sb.append(str + "   ");
            }
        }
    }

    private String LogData(byte[][] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                sb.append(array[i][j] + ",");
            }
        }
        return sb.toString();
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    private String jToStr(int j) {
        Calendar date = Calendar.getInstance();
        date.set(Calendar.HOUR_OF_DAY, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        long timeStamp = date.getTimeInMillis();
        timeStamp = timeStamp + j * 30 * 60 * 1000;
        String str = sdf.format(new Date(timeStamp));
        return str;
    }

    @Override
    public void onCheckedChanged(CompoundButton view, boolean isChecked) {
        switch (view.getId()) {
            case R.id.switch_record:
                if (isChecked) {
                    showViewContent();
                } else {
                    dissMissViewContent();
                }
                showjuHuaDialog();
                rec_param.u32Enable = isChecked ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_PARAM, rec_param.parseContent());
                break;
        }
    }

    private void dissMissViewContent() {
        ll_planvideo_content.setPivotY(0);
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_planvideo_content, "ScaleY", 1f, 0f);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(ll_planvideo_content, "Alpha", 1f, 0f);
        set.setDuration(350);
        set.setInterpolator(new AccelerateInterpolator());
        set.playTogether(animator, animator1);
        set.start();
    }

    private void showViewContent() {
        ll_planvideo_content.setVisibility(View.VISIBLE);
        ll_planvideo_content.setPivotY(0);
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_planvideo_content, "ScaleY", 0f, 1f);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(ll_planvideo_content, "Alpha", 0f, 1f);
        set.setDuration(350);
        set.setInterpolator(new AccelerateInterpolator());
        set.playTogether(animator, animator1);
        set.start();
    }
}
